<template>
  <div id="naturalMdrRuleDiv">
    <!-- <Breadcrumb content="天然耐药规则" /> -->
    <Splitpanes>
      <Pane size="100">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="findBacNaturalMdrRuleList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addNaturalMdrRule"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveNaturalMdrRuleList"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="batchDeleteBacNaturalMdrRule"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="mdrRuleTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="naturalMdrRuleList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>

            <vxe-column field="germNa" title="细菌" width="250" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/bac/germ/dict/getGermsByParams'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'germNo', title: '编码' },
              { field: 'germNa', title: '名称', } 
              ]" :aimKeys="[
               { aimKey: 'germNa', rowKey: 'germNa' },
               { aimKey: 'germNo', rowKey: 'germNo' }
              ]" :displayTexts="['germNa']" :displayTextObj="row.germNa ? row.germNa : ''" />
              </template>
            </vxe-column>

            <vxe-column field="antClassNa" title="抗生素分类" width="250" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/bac/ant/antClass/findBacAntClassList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'antClassNo', title: '编码' },
              { field: 'antClassNa', title: '名称', } 
              ]" :aimKeys="[
               { aimKey: 'antClassNa', rowKey: 'antClassNa' },
               { aimKey: 'antClassNo', rowKey: 'antClassNo' }
              ]" :displayTexts="['antClassNa']" :displayTextObj="row.antClassNa ? row.antClassNa : ''" />
              </template>
            </vxe-column>
            <vxe-column field="subClassNa" title="抗生素子分类" width="250" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/bac/ant/antSubClass/findBacAntSubClassList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'subClassNo', title: '编码' },
              { field: 'subClassNa', title: '名称', } 
              ]" :aimKeys="[
               { aimKey: 'subClassNo', rowKey: 'subClassNo' },
               { aimKey: 'subClassNa', rowKey: 'subClassNa' },
               { aimKey: 'antClassNo', rowKey: 'antClassNo' }
              ]" :displayTexts="['subClassNa']" :displayTextObj="row.subClassNa ? row.subClassNa : ''" :dataObj="{ antClassNo: row.antClassNo }" />
              </template>
            </vxe-column>
            <vxe-column field="antNa" title="抗生素" width="250" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">

                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/lis/bacAntibioticsDict/findAntDictList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'antCode', title: '编码' },
              { field: 'antName', title: '名称', } 
              ]" :aimKeys="[
               { aimKey: 'antNo', rowKey: 'antCode' },
               { aimKey: 'antNa', rowKey: 'antName' }
              ]" :displayTexts="['antNa']" :displayTextObj="row.antNa ? row.antNa : ''" :dataObj="{ antClassNo: row.antClassNo,subClassNo:row.subClassNo }" />
              </template>
            </vxe-column>
            <vxe-column field="seq" title="顺序" width="150" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.seq" placeholder="" type="text" clearable></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>

  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';

let naturalMdrRuleList: any = reactive([]); //左侧仪器表格数据
let rloading = ref(false);
let sltInstrSample: any = {};
defineExpose({ initPage });

function initPage() {
  findBacNaturalMdrRuleList();
}
onMounted(() => {
  //findBacNaturalMdrRuleList();
});

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findBacNaturalMdrRuleList() {
  rloading.value = true;
  naturalMdrRuleList.length = 0; //放入数据前清空数据
  const url = '/bac/ant/naturalMdrRule/findBacNaturalMdrRuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {}
    })
    .then((res: any) => {
      naturalMdrRuleList.push(...res.data);
      if (naturalMdrRuleList.length > 0) {
        sampleRowClick({ row: naturalMdrRuleList[0] });
      } else {
        sltInstrSample = {};
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 左侧新增
function addNaturalMdrRule() {
  const record: any = {
    id: '',
    germNo: '',
    antClassNo: '',
    subClassNo: '',
    antNo: '',
    orgId: ''
  };
  naturalMdrRuleList.push(record);
}
// 左侧保存
async function saveNaturalMdrRuleList() {
  let $Xtable = proxy.$refs.mdrRuleTableRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = naturalMdrRuleList.filter((e: any) => {
      return !e.id || e.id === '';
    });

    const sveOrupdateRules = [] as any[];
    updateRecords.forEach((e: any) => {
      const iIRule: any = {
        id: e.id,
        germNo: e.germNo,
        antClassNo: e.antClassNo,
        subClassNo: e.subClassNo,
        antNo: e.antNo,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.germNo)) {
        iIRule.germNo = '';
      }
      if (isEmpty(iIRule.antClassNo)) {
        iIRule.antClassNo = '';
      }
      if (isEmpty(iIRule.subClassNo)) {
        iIRule.subClassNo = '';
      }
      if (isEmpty(iIRule.antNo)) {
        iIRule.antNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });
    InsertRecords.forEach((e: any) => {
      const iIRule: any = {
        id: e.id,
        germNo: e.germNo,
        antClassNo: e.antClassNo,
        subClassNo: e.subClassNo,
        antNo: e.antNo,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.germNo)) {
        iIRule.germNo = '';
      }
      if (isEmpty(iIRule.antClassNo)) {
        iIRule.antClassNo = '';
      }
      if (isEmpty(iIRule.subClassNo)) {
        iIRule.subClassNo = '';
      }
      if (isEmpty(iIRule.antNo)) {
        iIRule.antNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });

    if (sveOrupdateRules.length > 0) {
      const url = '/bac/ant/naturalMdrRule/saveOrUpdateBacNaturalMdrRule';
      const obj: any = {};
      obj.bacNaturalMdrRuleList = sveOrupdateRules;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findBacNaturalMdrRuleList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}
// 左侧删除
function batchDeleteBacNaturalMdrRule() {
  const sltInstrSamples = (proxy.$refs.mdrRuleTableRef as any).getCheckboxRecords();
  if (!(sltInstrSamples.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delInstrSampleList = sltInstrSamples.filter((p: any) => !isEmpty(p.id));
        if (delInstrSampleList.length > 0) {
          const data = { bacNaturalMdrRuleList: delInstrSampleList };
          const url = '/bac/ant/naturalMdrRule/batchDeleteBacNaturalMdrRule';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findBacNaturalMdrRuleList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeInstrSampleList = sltInstrSamples.filter((p: any) => isEmpty(p.id));
        if (removeInstrSampleList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.mdrRuleTableRef;
          if ($Xtable) {
            for (const removeRow of removeInstrSampleList) {
              const iindex = naturalMdrRuleList.findIndex((item) => item == removeRow);
              naturalMdrRuleList.splice(iindex, 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 左侧表格 点击当前行
function sampleRowClick({ row }) {
  if (isEmpty(row)) {
    sltInstrSample = {};
  } else {
    (proxy.$refs.mdrRuleTableRef as any).setCurrentRow(row);
    sltInstrSample = row;
  }
}

function pulldownSelectConfirm(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      naturalMdrRuleList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
</script>

<style lang="scss" scoped>
#naturalMdrRuleDiv {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .roleTable {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>
